import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as anime
import scipy
from scipy import stats
# test 2.8.1_Entropy
def H(p):
h=0
for k in p:
h += -1*k*np.log2(k)
return h
H([0.25,0.25,0.2,0.15,0.15])
def KL(ArrayP,ArrayQ):
if len(ArrayP)!=len(ArrayQ):
print "Not mutch len(ArrayP) and len(ArrayQ)"
kl=0
for p,q in zip(ArrayP,ArrayQ):
#print p,q
kl +=p*np.log2(p/q)
return kl
def kl1(p,q):
p = np.array(p)
q = np.array(q)
p = p/p.sum()
q = q/q.sum()
return np.sum(p * np.log2(p / q), axis=(p.ndim - 1))
def kl2(p,q):
p = np.array(p)
q = np.array(q)
return np.sum(p * np.log2(p / q), axis=(p.ndim - 1))
def JSD(ArrayP,ArrayQ):
if len(ArrayP)!=len(ArrayQ):
print "Not mutch len(ArrayP) and len(ArrayQ)"
jsd=0
for p,q in zip(ArrayP,ArrayQ):
m = (p+q)/2
jsd +=0.5*( p*np.log2(p/m) ) + 0.5*( p*np.log2(p/m) )
return jsd
test1=np.random.rand(10000)
test2=np.random.rand(10000)
KL(test1,test2)
kl1(test1,test2)
kl2(test1,test2)
JSD(test1,test2)
stats.entropy(test1,test2,base=2)
test1
test1=np.array(test1)
test1
x=np.array(range(0,10000))
fig = plt.figure()
fig = plt.figure()
ax1 = fig.add_subplot(2,2,1)
ax2 = fig.add_subplot(2,2,2)
ax3 = fig.add_subplot(2,2,3)
ax1.scatter(np.arange(10000),test1*100)
plt.show()
ax1.scatter(np.arange(10000),test1*100)
plt.show()
from ipython_animated_array import AnimateArray
import numpy as np
initial = np.random.randint(2, size=(10,10))
AnimateArray([initial], cmap='winter').show()
def get_next(current):
next_state = []
for i in range(10):
next_row = []
for j in range(10):
living = current[i-1][j-1] + current[i-1][j] + current[i-1][(j+1)%10] + \
current[i][j-1] + current[i][j] + current[i][(j+1)%10] + \
current[(i+1)%10][j-1] + current[(i+1)%10][j] + current[(i+1)%10][(j+1)%10]
next_row.append(1 if living in (3,4) else 0)
next_state.append(next_row)
return next_state
states = [initial]
current = initial
for i in range(1000):
current = get_next(current)
states.append(np.array(current))
test = np.array(states)
print test.shape
AnimateArray(states, cmap='winter').show(reflesh=400)